package com.ccb.p4.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccb.p4.common.ResultCodeEnum;
import com.ccb.p4.entity.Problem;
import com.ccb.p4.entity.vo.ProblemQuery;
import com.ccb.p4.exception.AppException;
import com.ccb.p4.mapper.ProblemMapper;
import com.ccb.p4.service.ProblemService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * p4问题错误表 服务实现类
 * </p>
 *
 * @author xianghui.zh
 * @since 2022-01-19
 */
@Service
public class ProblemServiceImpl extends ServiceImpl<ProblemMapper, Problem> implements ProblemService {

    @Override
    public void add(Problem problem) {
        this.save(problem);
    }

    @Override
    public List<Problem> listAll() {
        List<Problem> problems = baseMapper.selectList(null);
        return problems;
    }

    @Override
    public void pageQuery(Page<Problem> pagePram, ProblemQuery problemQuery) {
        QueryWrapper<Problem> queryWrapper = new QueryWrapper<>();
        String errorCode = problemQuery.getErrorCode();
        String errorAp = problemQuery.getErrorAp();
        String errorKeywords = problemQuery.getErrorDescription();
        String traceCode = problemQuery.getTraceCode();
        String transactionCode = problemQuery.getTransactionCode();
        // 错误码精确查找
        if (StringUtils.hasText(errorCode)) {
            queryWrapper.eq("error_code", errorCode);
        }
        // 环境精确查找
        if (StringUtils.hasText(errorAp)) {
            queryWrapper.eq("error_ap", errorAp);
        }
        // 错误描述关键字模糊查询
        if (StringUtils.hasText(errorKeywords)) {
            queryWrapper.like("error_description", errorKeywords);
        }
        // 流水号模糊查询
        if (StringUtils.hasText(traceCode)) {
            queryWrapper.like("trace_code", traceCode);
        }
        // 交易吗精确查找
        if (StringUtils.hasText(transactionCode)) {
            queryWrapper.eq("transaction_code", transactionCode);
        }
        // 按创建时间排序
        queryWrapper.orderByDesc("gmt_create");
        baseMapper.selectPage(pagePram, queryWrapper);
    }

    @Override
    public Problem findById(String id) {
        return this.getById(id);
    }

    @Override
    public boolean deleteById(Integer id) {
        Integer row = baseMapper.deleteById(id);
        return null != row && row > 0;
    }

    @Override
    public boolean updateProblem(Problem problem) {
        // 校验ID
        if (problem.getId() != null){
            Integer row = baseMapper.updateById(problem);
            return null != row && row > 0;
        }else {
            throw new AppException(ResultCodeEnum.ARGS_NULL_ERROR.getCode(),"id为空");
        }
    }
}
